
#include<stack>
using std::stack;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


class Solution {
public:
    bool isValidBST(TreeNode* root) {
        // 中序遍历后满足顺序即为合格的二叉搜索树
        int current;
        bool init = false;
        if (root == nullptr) return true;
        stack<TreeNode*> s;
        TreeNode *x = root;
        while (true) {
            while (x) {
                s.push(x);
                x = x->left;
            }
            if (s.empty()) break;
            x = s.top();
            s.pop();
            
            if (init && current >= x->val) return false;
            else if(!init) init = true;
            current = x->val;
            x = x->right;
        }
        return true;
    }

};